package com.kdd.campus.sh.controller;

import com.alibaba.fastjson.JSON;
import com.kdd.campus.common.entity.CommonResult;
import com.kdd.campus.common.util.RedisUtil;
import com.kdd.campus.sh.dto.LoginUserDto;
import com.kdd.campus.sh.po.Admin_user;
import com.kdd.campus.sh.po.User;
import com.kdd.campus.sh.service.UserService;
import com.kdd.campus.sh.util.JwtTokenUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @Auther: fcp
 * @Date: 2020/4/20 19:32
 * @Description:
 */
@RestController
@RequestMapping("login")
@Api("登录")
public class LoginController {

    @Autowired
    private UserService userService;

    @Value("${wechat.webAccessTokenhttps}")
    private String webAccessTokenhttps;

    @Value("${wechat.APPID}")
    private String APPID;

    @Value("${wechat.APPSecret}")
    private String APPSecret;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @ApiOperation(value = "微信登录",notes = "微信登录")
    @PostMapping("/wechat")
    public CommonResult loginByWechat(@RequestBody @Validated LoginUserDto userDto) {
        // 拼接请求微信的服务器获取微信用户的信息的url
        String url = String.format(webAccessTokenhttps, APPID, APPSecret, userDto.getCode());

        Map<String, Object> map = null;
        try {
            HttpClient client = HttpClientBuilder.create().build();//构建一个Client
            HttpGet get = new HttpGet(url);    //构建一个GET请求
            HttpResponse response = client.execute(get);//提交GET请求
            // 返回值中含有session_key和openId
            HttpEntity result = response.getEntity();//拿到返回的HttpResponse的"实体"
            String content = EntityUtils.toString(result);
            System.out.println(content);//打印返回的信息
            map = JSON.parseObject(content, Map.class);
            String openid = (String) map.get("openid");
            if (openid == null){
                return CommonResult.failed("登录失败,获取openId失败"+content);
            }

            // 将openId和用户信息存储到数据库中(如果已经存在就当作更新用户信息)
            User user = userService.login(openid, userDto);

            // 生成JWT令牌
//            JwtTokenUtil jwtTokenUtil = jwtTokenUtil();
            HashMap<String, Object> claimMap = new HashMap<>();
            claimMap.put("sub", userDto.getNickname());
            String token = jwtTokenUtil.generateToken(claimMap);

            // 以token作为key, userId作为value,写入Redis中
            RedisUtil.set(token, user.getId(),60*24*3);//3天

            // 将token返回给客户端
            return CommonResult.success(token);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed("登录失败"+e.getMessage());
        }
    }
    @ApiOperation(value = "用户登录",notes = "用户登录")
    @PostMapping("/login")
    public CommonResult loginByUserId(HttpServletRequest request) {
        Long userId =Long.parseLong(request.getParameter("userId"));
        String password=request.getParameter("password");
        Admin_user admin_user=userService.findAdminById(userId);
        if(admin_user==null){
            return CommonResult.failed("登录失败,该用户不存在");
        }else if(!admin_user.getPassword().equals(password)){
            return CommonResult.failed("登录失败,输入账号或密码错误");
        }else{
            return CommonResult.failed("登录成功");
        }



    }

}
